package com.cqz.action;

import com.cqz.dao.BookInfo;
import com.cqz.dao.UserInfo;
import com.cqz.services.BookService;
import com.cqz.services.TagService;
import com.cqz.services.UserService;
import com.cqz.tools.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Controller
public class HomeAction {
    @Autowired
    private UserService userService;

    @Autowired
    private TagService tagService;

    @Autowired
    private BookService bookService;

    /**
     * 登录或注册之后，得到用户相关信息，更新推荐内容，进入主页
     * @param model
     * @param httpSession
     * @return
     */
    @RequestMapping("homeAction")
    public String execute(Model model, HttpSession httpSession) {
        boolean isLogin = (boolean)httpSession.getAttribute("isLogin");
        if(isLogin == false)
            return "fail";

        String user_name = (String)httpSession.getAttribute("user_name");  //获得用户名

        //接下来返回初始推荐列表
        String session_Id = httpSession.getId();
        int uid=(Integer) httpSession.getAttribute("uid");


        UserInfo userInfo=userService.findUser(uid);
        String[]tagList=new String[6];
        tagList[0]=userInfo.getUtag1();
        tagList[1]=userInfo.getUtag2();
        tagList[2]=userInfo.getUtag3();
        tagList[3]=userInfo.getUtag4();
        tagList[4]=userInfo.getUtag5();
        tagList[5]=userInfo.getUtag6();
        httpSession.setAttribute("tagList",tagList);
        httpSession.setAttribute("money",userInfo.getUamount());
        List<String> tags=new ArrayList<>();
        for(int i=0;i<6;i++){
            if(!Tools.isNull(tagList[i])){
                tags.add(tagList[i]);
            }
        }

        List<BookInfo> recommendList=new ArrayList<>();
        List<Integer> bids=tagService.getRecommendTags(tags);
        Iterator<Integer> iterator=bids.iterator();
        int index=0;
        while (iterator.hasNext()){
            if(index<4){
                BookInfo bookInfo=bookService.getBookById(iterator.next());
                recommendList.add(bookInfo);
                index++;
            }else {
                break;
            }
        }
        httpSession.setAttribute("recommendList",recommendList);
        return "main";
    }

    /**
     * 返回管理员主页
     * @param httpSession
     * @return
     */
    @RequestMapping("homeAdminAction")
    public String homeAdminAction(HttpSession httpSession){
        httpSession.removeAttribute("searchContent");
        httpSession.removeAttribute("berror");
        return "admin";
    }
}
